package Tracker.server.control;

import org.json.JSONException;
import org.json.JSONObject;

import Tracker.server.model.TError;
import Tracker.server.model.Session;
import Tracker.server.model.User;

public class LoginController {
	ProtocolHandler handler;
	
	public LoginController(ProtocolHandler h) {
		this.handler = h;
	}
	
	public void login(JSONObject req, JSONObject res) throws JSONException {
		/*
		 * {
		 * 	command : "login",
		 * 	user : {
		 * 		name : "",
		 * 		password : ""
		 * 	}
		 * }
		 * 
		 */
		try {
			JSONObject u = req.getJSONObject("user");
			
			try {
				String name = u.getString("name");
				String pass = u.getString("password");
				User user = null;
				
				if(!this.handler.model.containsUser(name)) {
					try {
						user = new User(this.handler.model.getUID(), name, pass);
						this.handler.model.addUser(user);
						
						this.handler.session = new Session(this.handler.model.getSID(), user);
						this.handler.model.addSession(this.handler.session);
						
						res.append("success", new Boolean(true));
						res.append("session", this.handler.session);
						return;
					} catch (Exception eee) {
						res.append("success", new Boolean(false));
						res.append("error", new TError("Missing user name or password", 400));
						return;
					}
				} else {
					user = this.handler.model.getUserByName(name);
					if(user.authenticate(name, pass)) {
						this.handler.session = new Session(this.handler.model.getSID(), user);
						this.handler.model.addSession(this.handler.session);
						
						res.append("success", new Boolean(true));
						res.append("session", this.handler.session);
						return;
					} else {
						res.append("success", new Boolean(false));
						res.append("error", new TError("Invalid name or password", 401));
					}
				}
			} catch (Exception ee) {
				res.append("success", new Boolean(false));
				res.append("error", new TError("Invalid user object", 400));
				
				ee.printStackTrace();
				return;
			}
		} catch (JSONException e) {
			res.append("success", new Boolean(false));
			res.append("error", new TError("No user object", 400));
			return;
		}
	}
	
	public void logout(JSONObject req, JSONObject res) throws JSONException {
		this.handler.model.removeSession(this.handler.session.id);
		res.append("success", new Boolean(true));
		return;
	}
}
